package com.sunnada.nginx.controller;

import com.alibaba.fastjson.JSON;
import com.sunnada.nginx.bean.nginx.http.HttpServer;
import com.sunnada.nginx.exception.CustonException;
import com.sunnada.nginx.service.ListenerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(value = "监听", description = "监听")
@RestController
@RequestMapping("listeners")
public class ListenerController {

    @Autowired
    ListenerService listenerService;

    @ApiOperation(value="获取监听列表", notes="获取监听列表",httpMethod = "GET")
    @GetMapping
    @ResponseBody
    public Object list() throws CustonException {
        return listenerService.list();
    }

    @ApiOperation(value="获取监听", notes="获取监听",httpMethod = "GET")
    @ApiImplicitParam(name = "nameAndPort", value = "服务器名称和端口", required = true, dataType = "String", paramType = "path",example = "localhost:80")
    @GetMapping("/{nameAndPort}")
    @ResponseBody
    public String one(@PathVariable String nameAndPort) throws CustonException {
        return listenerService.one(nameAndPort).toJson();
    }

    @ApiOperation(value="新增监听", notes="新增监听",httpMethod = "POST")
    @PostMapping
    @ResponseBody
    public String post(HttpServer httpServer) throws CustonException {
//        HttpServer httpServer = JSON.parseObject(json, HttpServer.class);
        return listenerService.post(httpServer)?"success":"fail";
    }

    @ApiOperation(value="修改监听", notes="修改监听",httpMethod = "PUT")
    @PutMapping
    @ResponseBody
    public String put(HttpServer httpServer) throws CustonException {
//        HttpServer httpServer = JSON.parseObject(json, HttpServer.class);
        return listenerService.put(httpServer)?"success":"fail";
    }

    @ApiOperation(value="删除监听", notes="删除监听",httpMethod = "DELETE")
    @ApiImplicitParam(name = "nameAndPort", value = "服务器名称和端口", required = true, dataType = "String", paramType = "path",example = "localhost:80")
    @DeleteMapping("/{nameAndPort}")
    @ResponseBody
    public String delete(@PathVariable String nameAndPort) throws CustonException {
        return listenerService.delete(nameAndPort)?"success":"fail";
    }
}
